package com.fjeld.middleware.activemq;

import com.fjeld.middleware.jaxb.V1Heartbeat;
import com.fjeld.middleware.util.collection.HeartbeatHashmap;
import com.fjeld.middleware.util.collection.ObservableArrayList;
import com.fjeld.middleware.util.collection.ObservableHashMap;
import com.fjeld.middleware.util.serverstatus.ServerStatusCapsule;
import com.fjeld.server.store.reader.XMLKit;
import org.apache.log4j.Logger;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.swing.text.DateFormatter;
import java.io.Serializable;
import java.text.DateFormat;
import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: fjeld
 * Date: 11/12/2011
 * Time: 17:51
 *
 * Listens for any heartbeats. Adds source to the map, allowing anyone interested to monitor the map and
 * consequently the presence of the sources.
 */
public class HeartbeatListener extends TopicListener
{
    private static final Logger LOGGER = Logger.getLogger(HeartbeatPublisher.class);
    private HeartbeatHashmap<String, ServerStatusCapsule> serverMap =
            new HeartbeatHashmap<String, ServerStatusCapsule>(20);
    private ObservableArrayList serverList = new ObservableArrayList(20);

    public HeartbeatListener(String topicString, String publisherName) throws JMSException
    {
        super(topicString, publisherName);
        LOGGER.info(publisherName);

    }

    public ObservableHashMap getServerMap()
    {
        return serverMap;
    }

    public ObservableArrayList getServerList()
    {
        return serverList;
    }

    public void startConnection()
    {
        super.startConnection();
    }

    public void onMessage(Message message)
    {
        ObjectMessage objMsg = (ObjectMessage) message;

        try
        {
            Serializable msg = objMsg.getObject();
//            LOGGER.info(logPrefix + "Received:\n" + XMLKit.xmlObjToString(msg));

            if (msg instanceof V1Heartbeat)
            {
                V1Heartbeat v1Heartbeat = (V1Heartbeat) msg;
                if (!serverMap.containsKey(v1Heartbeat.getServername()))
                {
                    ServerStatusCapsule ssc = new ServerStatusCapsule(v1Heartbeat);
                    serverMap.put(v1Heartbeat.getServername(), ssc);
                    serverList.add(ssc);
                } else
                {
                    serverMap.get(v1Heartbeat.getServername()).update(v1Heartbeat);
                }
            }
        } catch (JMSException e)
        {
            LOGGER.error(logPrefix + "Could not unmarshal message:", e);
        }
    }
}
